package com.sd.app;

import java.io.File;

import android.content.Context;
import android.os.Environment;

import com.alex.books.BookPageFactory;
import com.sd.util.PreferencesManager;
import com.sd.util.SIMCardInfo;

public class AppInit {

	private static AppInit instance;
	
	private SIMCardInfo mSim;
	public String APP_DIR = "";
	public String APP_DB = "";
	public String APP_BOOKS = "";
	public int screenW;
	public int screenH;
	public int density;
	
	
	public static AppInit getInstance() {
		if (instance == null) {
			instance = new AppInit();
		}
		return instance;
	}

	
	public void init(Context context,String sdcardDir) {
		
		mSim = new SIMCardInfo(context);
		String appDir = PreferencesManager.getInstance().getDir();
		if(appDir==null || "".equals(appDir)){
			//判断是否有存储卡
			if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
				StringBuffer sbuf = new StringBuffer();
				sbuf.append(Environment.getExternalStorageDirectory().getAbsolutePath());
				sbuf.append("/");
				sbuf.append(sdcardDir);
				sbuf.append("/");
				APP_DIR = sbuf.toString();
			}else{
				StringBuffer sbuf = new StringBuffer();
				sbuf.append("/data/data/");
				sbuf.append(context.getPackageName());
				sbuf.append("/files/");
				APP_DIR = sbuf.toString();
			}
			File dir = new File(APP_DIR);
			dir.mkdir();
			PreferencesManager.getInstance().setSDDir(APP_DIR);
		}else{
			APP_DIR = appDir; 
		}
		
		if(PreferencesManager.getInstance().getISFirst()){
			deleteFile(AppInit.getInstance().APP_DIR);
		}
		
		APP_DB = APP_DIR+"db/";
		APP_BOOKS = APP_DIR+"books/";
		
		File f = new File(APP_DIR);
		if(!f.exists()){
			f.mkdir();
		}
		f = new File(APP_BOOKS);
		if(!f.exists()){
			f.mkdir();
		}
		BookPageFactory.getInstance().setDBDir(APP_DB);
		
	}
	
	public SIMCardInfo getSIM(){
		return mSim;
	}
	

	private void deleteFile(String path) {
		File file = new File(path);
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					this.deleteFile(files[i].getAbsolutePath()); // 把每个文件 用这个方法进行迭代
				}
			}
			file.delete();
		} else {
			System.out.println("所删除的文件不存在！" + '\n');
		}
	}
}
